package com.ywjt.platformbusiness.store.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.base.BaseModel;
import com.ywjt.platformbusiness.common.UserData;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.my.model.CitysBean;
import com.ywjt.platformbusiness.store.model.BusinessCenterMsgModle;
import com.ywjt.platformbusiness.util.CitySelectUtils;
import com.ywjt.platformbusiness.util.GlideEngine;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.PictureUtils;
import com.ywjt.platformbusiness.util.SoftKeyboardUtils;
import com.ywjt.platformbusiness.util.StrUtils;
import com.ywjt.platformbusiness.util.ToastUtil;
import com.ywjt.platformbusiness.widget.PhotoPickBottomDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ywjt.platformbusiness.common.MethodUtils.getUserId;

public class ActivityBusinessInfo extends BaseActivity implements View.OnClickListener {
    /***
     * 修改信息   确认修改
     * */
    private CitysBean citysBean1;
    private EditText etStoreName,etOpenTime,etStorePhone,etOwner,etOwnerPhone,etaddressDetail;
    private ImageView ivStoreLogo;
    private TextView tvModify,etAddress;
    private LinearLayout llAddress;
    private Boolean isEdit=false;

    private String address="",businessHours="",detailAddress="",shopLogo="",
            shopName="",shopPhone="",shopPhoto="",principalName="",principalPhone="";

    private String businessLicense="";//营业执照

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, ActivityBusinessInfo.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llAddress:
                //三级联动地址选择器
                SoftKeyboardUtils.hideSoftKeyboard(this);
                citysBean1 = JSON.parseObject(StrUtils.getJson("startAddress.json", getContext()), CitysBean.class);
                CitySelectUtils citySelectUtils = new CitySelectUtils(getContext(), citysBean1);
                citySelectUtils.setCityCallBack(new CitySelectUtils.CityCallBack() {
                    @Override
                    public void city(String province, String city, String county) {
                        if (county.equals("全部")) {
                            address = province + " " + city;//如果区级是全部就给后台传省级/市级
                        } else {
                            address = province + " " + city + " " + county;//如果全有给后台传省级/市级/区级
                        }
                        etAddress.setText(address);
                    }
                    @Override
                    public void cancle() { }
                });
                break;
            case R.id.ivStoreLogo:
                PhotoPickBottomDialog pickBottomDialog=new PhotoPickBottomDialog();
                pickBottomDialog.setClicklistener(new PhotoPickBottomDialog.ClickListenerInterface() {
                    @Override
                    public void takePhoto() {
                        //拍照并剪裁
                        PictureSelector.create( ActivityBusinessInfo.this)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.SINGLE)
                                .isCamera(true)
                                .compressQuality(100)
                                .compress(true)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.REQUEST_CAMERA);
                    }

                    @Override
                    public void selectFromAlbum() {
                        PictureSelector.create( ActivityBusinessInfo.this)
                                .openGallery(PictureMimeType.ofImage())
                                .selectionMode(PictureConfig.SINGLE)
                                .isCamera(false)
                                .compressQuality(100)
                                .compress(true)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                    }
                });
                pickBottomDialog.show(getSupportFragmentManager());
                break;
            case R.id.tvModify:
                if (!isEdit){
                    reSetStatus();
                    tvModify.setText("确认修改");
                }else {
                    if (path.equals("")){
                        updateBusinessInfo();
                    }else {
                        uploadImg(path);
                    }
                }
                isEdit=!isEdit;
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_store_info;
    }

    @Override
    protected void initView() {
        setTitleText("店铺信息");
        tvModify=findViewById(R.id.tvModify);
        etStoreName=findViewById(R.id.etStoreName);
        ivStoreLogo=findViewById(R.id.ivStoreLogo);
        etOpenTime=findViewById(R.id.etOpenTime);
        etStorePhone=findViewById(R.id.etStorePhone);
        etOwner=findViewById(R.id.etOwner);
        etOwnerPhone=findViewById(R.id.etOwnerPhone);
        etAddress=findViewById(R.id.etAddress);
        etaddressDetail=findViewById(R.id.etaddressDetail);
        llAddress=findViewById(R.id.llAddress);
        tvModify.setOnClickListener(this::onClick);
        ivStoreLogo.setOnClickListener(this::onClick);
        llAddress.setOnClickListener(this::onClick);
        getCenterData();
        setStatus();


        //负责人
        etOwner.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                principalName=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //店铺名称
        etStoreName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                shopName=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //营业时间
        etOpenTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                businessHours=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //门店电话
        etStorePhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                shopPhone=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //负责人电话
        etOwnerPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                principalPhone=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //详细地址
        etaddressDetail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                detailAddress=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public void setStatus(){
        etStoreName.setFocusable(false);
        etStoreName.setFocusableInTouchMode(false);
        etOpenTime.setFocusable(false);
        etOpenTime.setFocusableInTouchMode(false);
        etStorePhone.setFocusableInTouchMode(false);
        etStorePhone.setFocusable(false);
        etOwner.setFocusable(false);
        etOwner.setFocusableInTouchMode(false);
        etOwnerPhone.setFocusable(false);
        etOwnerPhone.setFocusableInTouchMode(false);
        etaddressDetail.setFocusableInTouchMode(false);
        etaddressDetail.setFocusable(false);
        etAddress.setFocusable(false);
        etAddress.setFocusableInTouchMode(false);
        ivStoreLogo.setClickable(false);
    }
    public void reSetStatus(){
        etStoreName.setFocusable(true);
        etStoreName.setFocusableInTouchMode(true);
        etOpenTime.setFocusable(true);
        etOpenTime.setFocusableInTouchMode(true);
        etStorePhone.setFocusableInTouchMode(true);
        etStorePhone.setFocusable(true);
        etOwner.setFocusable(true);
        etOwner.setFocusableInTouchMode(true);
        etOwnerPhone.setFocusable(true);
        etOwnerPhone.setFocusableInTouchMode(true);
        etaddressDetail.setFocusableInTouchMode(true);
        etaddressDetail.setFocusable(true);
        etAddress.setFocusable(true);
        etAddress.setFocusableInTouchMode(true);
        ivStoreLogo.setClickable(true);

    }


    //修改商户信息
    public void updateBusinessInfo(){
        JSONObject map = new JSONObject();
        try {
            map.put("id",UserData.create(ActivityBusinessInfo.this).get(UserData.MERCHANTID));
            if (!address.equals("")){
                map.put("address",address);
            }
            if (!businessHours.equals("")){
                map.put("businessHours",businessHours);
            }
            if(!detailAddress.equals("")){
                map.put("detailAddress",detailAddress);
            }

            if (!principalName.equals("")){
                map.put("principalName",principalName);
            }

            if (!shopLogo.equals("")){
                map.put("shopLogo",shopLogo);
            }
            if (!shopName.equals("")){
                map.put("shopName",shopName);
            }
            if (!shopPhone.equals("")){
                map.put("shopPhone",shopPhone);
            }

            if (!shopPhoto.equals("")){
                map.put("shopPhoto",shopPhoto);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(getContext()).doPost(UrlConstants.merchant_updateShopMessage, "", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        getCenterData();
                        tvModify.setText("修改信息");
                        reSetStatus();
                    }else {
                        Toast.makeText(ActivityBusinessInfo.this,message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    private void getCenterData() {

        new HttpRequest(getContext()).doPost(UrlConstants.merchant_getShopMessage+ UserData.create(this).get(UserData.MERCHANTID), "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), BusinessCenterMsgModle.class);
                        if (obj instanceof BusinessCenterMsgModle) {
                            BusinessCenterMsgModle model = (BusinessCenterMsgModle) obj;
                            Glide.with(ActivityBusinessInfo.this).load(model.getResult().getShopLogo())
                                    .placeholder(R.mipmap.icon_business_logo)
                                    .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
                                    .into(ivStoreLogo);

                            etStoreName.setHint(model.getResult().getShopName());
                            etOpenTime.setHint(model.getResult().getBusinessHours());
                            etStorePhone.setHint(model.getResult().getShopPhone());
                            etOwner.setHint(model.getResult().getPrincipalName());
                            etOwnerPhone.setHint(model.getResult().getShopPhone());
                            etaddressDetail.setHint(model.getResult().getDetailAddress());
                            etAddress.setText(model.getResult().getAddress());
                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }



    @Override
    protected void initData() { }

    @Override
    protected int getTitleBarType() {
        return 0;
    }

    public void uploadImg(String path){
        new HttpRequest(ActivityBusinessInfo.this).doUploadFile(UrlConstants.common_upload, "", "file", new File(path), new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        shopLogo=message;
                        updateBusinessInfo();
                    }else {
                        ToastUtil toastUtil = new ToastUtil(getContext(), R.layout.popu_success1, message, 1);
                        toastUtil.show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }

    String path="";
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                case PictureConfig.REQUEST_CAMERA:
                    // 结果回调
                    List<LocalMedia> cameraList = PictureSelector.obtainMultipleResult(data);
                    if(cameraList.size()>0){
                        path=cameraList.get(0).getRealPath();
                    }
                    Glide.with(ActivityBusinessInfo.this).load(path)
                            .placeholder(R.mipmap.default_headlink)
                            .apply(new RequestOptions().transforms(new CenterCrop(), new RoundedCorners(10)))
                            .into(ivStoreLogo);
                    break;
                default:
                    break;
            }
        }
    }
}
